const express = require('express')
const router = express.Router();
let multiparty = require("multiparty")
let fs = require("fs")
const os = require('os');
const publicPath = process.env.UPLOAD_DIR || os.tmpdir();
const path = require('path');
router.post('/gotoAPK', function (req, res) {
    console.log("进入上传apk");
    // 获取请求中的 project_name 和 msg 参数，并解码
    let { project_name} = req.query;
    project_name = decodeURIComponent(project_name);
    // 生成项目目录路径
    const projectDir = path.join(publicPath, 'static', project_name);
    // 创建项目目录
    if (!fs.existsSync(projectDir)) {
        fs.mkdirSync(projectDir, { recursive: true });
    }
    let form = new multiparty.Form();
    // 设置上传文件的存储目录
    form.uploadDir = projectDir;
    // 设置上传文件的大小限制
    form.maxFilesSize = 20000000 * 1024 * 1024;
    // 解析表单数据
    form.parse(req, function (err, fields, files) {
        try {
            // 检查是否有文件上传
            if (!files || !files.hasOwnProperty('pic_path') || !Array.isArray(files.pic_path) || files.pic_path.length === 0) {
                console.log("未上传文件");
                res.status(400).json({ error: "未上传文件" });
                return;
            }

            // 获取上传的文件信息
            let uploadedFile = files.pic_path[0];
            let filename = "auto.apk"
            let fileType = uploadedFile.headers['content-type'];
            // 处理文件，例如保存到指定目录
            let newPath = path.join(projectDir, filename);
            fs.renameSync(uploadedFile.path, newPath);
            // 保存 msg 到 msg.txt

            res.json({
                code: "0",
                msg: "上传成功",
                filename: filename,
            });
        } catch (err) {
            console.log(err);
            res.json({
                code: "-1",
                msg: "上传错误!"
            });
        }
    });
});
router.post('/gotoupFile', function (req, res) {
    console.log("进入上传ice");

    // 获取请求中的 project_name 和 msg 参数，并解码
    let { project_name, msg } = req.query;
    project_name = decodeURIComponent(project_name);
    msg  = decodeURIComponent(msg);

    // 生成项目目录路径
    const projectDir = path.join(publicPath, 'static', project_name);

    console.log("进入ec热更新:" + project_name);

    // 创建项目目录
    if (!fs.existsSync(projectDir)) {
        fs.mkdirSync(projectDir, { recursive: true });
    }

    let form = new multiparty.Form();

    // 设置上传文件的存储目录
    form.uploadDir = projectDir;

    // 设置上传文件的大小限制
    form.maxFilesSize = 20000000 * 1024 * 1024;

    // 解析表单数据
    form.parse(req, function (err, fields, files) {
        try {
            // 检查是否有文件上传
            if (!files || !files.hasOwnProperty('pic_path') || !Array.isArray(files.pic_path) || files.pic_path.length === 0) {
                console.log("未上传文件");
                res.status(400).json({ error: "未上传文件" });
                return;
            }

            // 获取上传的文件信息
            let uploadedFile = files.pic_path[0];
            let filename = uploadedFile.originalFilename;
            let fileType = uploadedFile.headers['content-type'];

            // 处理文件，例如保存到指定目录
            let newPath = path.join(projectDir, filename);
            fs.renameSync(uploadedFile.path, newPath);

            // 更新版本号
            let versionFilePath = path.join(projectDir, 'version.txt');
            let version = 0;
            if (fs.existsSync(versionFilePath)) {
                version = parseInt(fs.readFileSync(versionFilePath, 'utf-8')) || 0;
            }
            version++;
            fs.writeFileSync(versionFilePath, version.toString());

            // 保存 msg 到 msg.txt
            let msgFilePath = path.join(projectDir, 'msg.txt');
            fs.writeFileSync(msgFilePath, msg);

            res.json({
                code: "0",
                msg: "上传成功",
                filename: filename,
                fileType: fileType,
                version: version
            });
        } catch (err) {
            console.log(err);
            res.json({
                code: "-1",
                msg: "上传错误!"
            });
        }
    });
});
router.get("/getVersion", async (req, res) => {
    console.log("有人访问了!");
    let project_name = decodeURIComponent(req.query.project_name || ''); // 解码项目名称，如果不存在则为空字符串
    let IP = decodeURIComponent(req.query.IP || ''); // 解码项目名称，如果不存在则为空字符串
    
    let versionFilePath = path.join(publicPath, 'static', project_name, 'version.txt'); // 组装版本文件路径
    let msgFilePath = path.join(publicPath, 'static', project_name, 'msg.txt'); // 组装 msg 文件路径

    try {
        let oldVersion = fs.readFileSync(versionFilePath, 'utf-8'); // 读取版本号

        let msg = ''; // 初始化 msg
        if (fs.existsSync(msgFilePath)) {
            msg = fs.readFileSync(msgFilePath, 'utf-8'); // 读取 msg
        }

        let time = new Date().getTime(); // 获取当前时间戳
        let download_url = `http://${IP}/ecjbUpFile/retice?time=${time}&project_name=${project_name}`; // 构建下载链接

        // 构建返回对象
        let 返回 = {
            download_url: download_url,
            version: oldVersion + ".0.0.0",
            dialog: true,
            msg: `请更新到最新版 ${oldVersion}，更新内容：${msg}`
        };

        console.log("fangwen", req.query);
        console.log("返回", 返回);
        res.send(返回); // 发送响应
    } catch (error) {
        console.error("获取版本号失败:", error.message);
        res.status(500).send({ error: "获取版本号失败" }); // 发送错误响应
    }
});
router.get("/retice", async (req, res) => {
    try {
        let project_name = decodeURIComponent(req.query.project_name || ''); // 解码项目名称，如果不存在则为空字符串
        let filePath = path.join(publicPath, 'static', project_name, 'release.iec'); // 组装文件路径

        // 检查文件是否存在
        if (!fs.existsSync(filePath)) {
            console.error(`文件不存在: ${filePath}`);
            return res.status(404).send('File Not Found');
        }

        const fileName = 'release.iec'; // 文件名
        res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`); // 设置响应头，指示浏览器下载文件
        const fileStream = fs.createReadStream(filePath);
        fileStream.pipe(res); // 将文件流管道连接到响应流
    } catch (error) {
        console.error('Error handling request:', error);
        res.status(500).send('Internal Server Error');
    }
});
router.get("/getapk", async (req, res) => {
    try {
        let project_name = decodeURIComponent(req.query.project_name || ''); // 解码项目名称，如果不存在则为空字符串
        let filePath = path.join(publicPath, 'static', project_name, 'auto.apk'); // 组装文件路径

        // 检查文件是否存在
        if (!fs.existsSync(filePath)) {
            console.error(`文件不存在: ${filePath}`);
            return res.status(404).send('File Not Found');
        }
        const fileName = 'auto.apk'; // 文件名
        res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`); // 设置响应头，指示浏览器下载文件
        const fileStream = fs.createReadStream(filePath);
        fileStream.pipe(res); // 将文件流管道连接到响应流
    } catch (error) {
        console.error('Error handling request:', error);
        res.status(500).send('Internal Server Error');
    }
});
function getLocalIP() {
    const interfaces = os.networkInterfaces();
    const ipv4Interfaces = interfaces['Ethernet'] || interfaces['Wi-Fi'] || interfaces['en0'] || interfaces['eth0'] || interfaces[null] || interfaces[undefined];

    let localIP = '';

    if (ipv4Interfaces) {
        ipv4Interfaces.forEach(interface => {
            if (interface.family === 'IPv4' && !interface.internal) {
                localIP = interface.address;
            }
        });
    } else {
        console.log('No suitable network interface found.');
    }

    return localIP;
}


module.exports = router;